前面我们有说过了 ssh 链接,今天我们来看看,怎么通过 C# ping 一个主机,以判断主机是否可达。
C# 中,ping 位于 System.Net.NetworkInformation 名称空间,你需要在程序的开始通过 using 引用该名称空间,才可以使用 ping。
下面我们来一起看看具体的实现代码:
using System;
using System.Net.NetworkInformation;
using System.Text;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Ping pingSender = new Ping(); // 新建一个 ping 类
PingOptions pingOptions = new PingOptions();
pingOptions.DontFragment = true;
string data = "ping test data"; // 定义 ping 发送的数据包
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 120;
Console.WriteLine("Please enter a IP address:");
string ip = Console.ReadLine();
PingReply reply = pingSender.Send(ip, timeout, buffer, pingOptions);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine("Address: " + reply.Address.ToString());
Console.WriteLine("RoundTrip time: " + reply.RoundtripTime);
Console.WriteLine("Time to live: " + reply.Options.Ttl);
Console.WriteLine("Don't fragment: " + reply.Options.DontFragment);
Console.WriteLine("Buffer size: " + reply.Buffer.Length);
}
}
}
}
代码说明:
运行结果: